package io.nads.service;

import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.SystemMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class QWenService {
    @Value("${llm.qwen.api.key}")
    private String apiKey;

    @Value("${llm.qwen.base.url}")
    private String baseUrl;

    private ChatModel chatModel;

    public String chat(List<ChatMessage> messages) {
        if (chatModel == null) {
            chatModel = OpenAiChatModel.builder()
                    .apiKey(apiKey)
                    .baseUrl(baseUrl)
                    .modelName("qwen-turbo")
                    .build();
        }

        AiMessage response = chatModel.chat(messages).aiMessage();
        return response.text();
    }

    public String chat(String userMessage) {
        if (chatModel == null) {
            chatModel = OpenAiChatModel.builder()
                    .apiKey(apiKey)
                    .baseUrl(baseUrl)
                    .modelName("qwen-turbo")
                    .build();
        }

        return chatModel.chat(userMessage);
    }

    public String chatWithSystem(String systemPrompt, String userMessage) {
        if (chatModel == null) {
            chatModel = OpenAiChatModel.builder()
                    .apiKey(apiKey)
                    .baseUrl(baseUrl)
                    .modelName("qwen-turbo")
                    .build();
        }

        List<ChatMessage> messages = new ArrayList<>();
        messages.add(SystemMessage.from(systemPrompt));
        messages.add(UserMessage.from(userMessage));

        AiMessage response = chatModel.chat(messages).aiMessage();
        return response.text();
    }

    public String chatWithSystem(String systemPrompt, List<ChatMessage> userMessages) {
        if (chatModel == null) {
            chatModel = OpenAiChatModel.builder()
                    .apiKey(apiKey)
                    .baseUrl(baseUrl)
                    .modelName("qwen-turbo")
                    .build();
        }

        List<ChatMessage> messages = new ArrayList<>();
        messages.add(SystemMessage.from(systemPrompt));
        messages.addAll(userMessages);

        AiMessage response = chatModel.chat(messages).aiMessage();
        return response.text();
    }
}
